package www.wackyboy.top.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import www.wackyboy.top.Employee;
import www.wackyboy.top.UserLogin;
import www.wackyboy.top.service.IUserService;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @Author: WackyBoy
 * @Date: 2021/1/4 20:02
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/all")
    public ResponseEntity<List<Employee>> queryAllUserInfo() {
        List<Employee> userList = this.userService.queryAllInfo();
        return ResponseEntity.ok(userList);
    }

    @PostMapping("/edit")
    public ResponseEntity<Employee> editUserInfo(@RequestBody Employee employee) {
        Integer flag = this.userService.saveUserInfo(employee);
        if(flag == 1) return  ResponseEntity.status(HttpStatus.CREATED).build();
        else return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }

    @PostMapping("/addUser")
    public ResponseEntity<Void>addUserInfo(@RequestBody Employee employee){
        Integer flag = this.userService.addUserInfo(employee);
        if(flag == 1) return  ResponseEntity.status(HttpStatus.CREATED).build();
        else return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }

    @PostMapping("/deleteUserById/{id}")
    public ResponseEntity<Void>deleteUserInfo(@PathVariable("id") String id){
        Integer flag = this.userService.deleteUserInfo(Integer.parseInt(id));
        if(flag == 1) return  ResponseEntity.status(HttpStatus.CREATED).build();
        else return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }

    @GetMapping("/searchUserByName")
    public ResponseEntity<List<Employee>>searchUserInfo(@RequestParam("name") String name) throws UnsupportedEncodingException {
        // 解决后端传中文参数乱码的问题
        name = new String(name.getBytes("iso-8859-1"),"utf-8");
        List<Employee> userList= this.userService.searchUserInfo(name);
        if(CollectionUtils.isEmpty(userList)) return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        else return ResponseEntity.ok(userList);
    }

    @PostMapping("/deleteUserBatch")
    public ResponseEntity<Void> deleteUserBatch(@RequestBody List<Integer> idList) {
        Integer flag = this.userService.deleteUserByBatch(idList);
        if(flag == 0) return ResponseEntity.status(HttpStatus.CREATED).build();
        else return  ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }

    @PostMapping("/checkUser")
    public ResponseEntity<Employee> checkUserInfo(@RequestBody UserLogin user) {
        Employee employee = this.userService.checkUserInfo(user);
        return ResponseEntity.ok(employee);
    }






}

